<?php
namespace Home\Controller;

use Utuo\DistributionShopForeground;
use Home\Logic\PayLogic;
use My\Model\OrderModel;
use Home\Logic\OrderLogic;

class PayXController extends DistributionShopForeground {
    
    /**
     * 设置订单业务类
     */
    protected function setOrderLogic( $uid ) {
        OrderLogic::setDriver(OrderModel::ORDER_TYPE_COMMON, array(
            'cid' => $this->cid,
            'uid' => $uid ? $uid : $this->uid,
        ));
    }
	
	public function _init() {
		layout('disshop');
		$this->setModelName("DistributionShop");
		$this->setModelControllerName("DisShop");
		$this->setSupportRedirect(false);
		if ( in_array(ACTION_NAME, array('notify', 'pay', 'notifyInvite')) ) { // 排除不验证登录的动作
			$this->setCheckLogin(false);
		}
		$this->uid and $this->setOrderLogic();
	}
	
	/**
	 * 转入支付接口
	 * @param payVo $vo 订单数据
	 */
	public function toPayAction() {
		$orderId = I("id", 0); // 订单id
		$apitype = I('apitype', ''); // 获得支付方式
		$backUrl = I('backUrl', ''); // 支付返回的链接
		$apiConfig = $this->getApiConfig(array('paymentMethod' => $apitype));
		// 获得订单
		if ( $orderId ) {
			$this->rwSeparate(0);
			$order = M("Order")->where("id=%d", $orderId)->find() or $this->error("订单无效($orderId)!");
			$this->rwSeparate(1);
		}
		// 检查重复支付
		if( $order['pay_status'] ) {
			$this->error("已经付过款了。", $backUrl); exit();
		}
		// 0元订单处理
		if ( $order['actual_cost']*1 <= 0 ) {
			$this->paySuccess($order['order_no'], $apitype);
			$this->success("准备收货吧。", $backUrl); exit();
		}
		// 处理结算方式
		if($apitype == "COD") {
			M("Order")->where("id=%d", $orderId)
					->save( array( "order_status" => \My\Model\ProductOrderModel::ORDER_STATUS_SHIPPING, 
							"pay_method" => $apitype,
							"confirm_time" => time(),
					) );
			$this->success("准备收货吧。", $backUrl); exit();
		} elseif(empty($apitype) or empty($apiConfig)) {
			$this->error("请选择结算方式。"); exit();
		}
		$vo = $this->parseOrder( $order );
		// 支付接口附加参数
		$apiConfig['wparam'] = array_merge($apiConfig['wparam'], array(
			'backUrl' => $backUrl, // 支付成功后的返回页面
		));
		// 获得支付接口
		$pay = \Utuo\Pay::getInstance($apitype, $apiConfig);
		// 生成支付表单
		$formHtml = $pay->buildRequestForm($vo);
		if ( IS_AJAX ) {
			$this->success("", "", array('payForm'=>$formHtml)); exit();
		} else {
			header("Content-Type:text/html;charset=utf-8");
			exit( $formHtml );
		}
	}
	
	/**
	 * 通知回调连接
	 */
	public function notifyAction() {
		$apitype = I('get.apitype', ''); // 获得支付方式
		$pay = \Utuo\Pay::getInstance($apitype, $this->getApiConfig(array('paymentMethod' => $apitype)));
		switch ($apitype) {
			case "Tenpay":
				$paramNames = "sign_type,service_version,input_charset,sign,sign_key_index,trade_mode,trade_state,pay_info,partner,bank_type,bank_billno,total_fee,fee_type,notify_id,transaction_id,out_trade_no,attach,time_end,transport_fee,product_fee,discount,buyer_alias";
				foreach(explode(",", $paramNames) as $v) {
					$notify[$v] = $_REQUEST[$v];
				}
				if( $pay->verifyNotify($notify) ) {
					$this->paySuccess($notify["out_trade_no"], $apitype);
				}
				exit();
			case "WxTenpay":
				if (isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
					// 处理数据
					$notify = (array) simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA'], 'SimpleXMLElement', LIBXML_NOCDATA);
					if( $pay->verifyNotify($notify) ) {
						$this->paySuccess($notify["out_trade_no"], $apitype);
						exit("<xml><return_code>SUCCESS</return_code></xml>");
					}
				} else {
					exit("<xml><return_code>FAIL</return_code></xml>");
				}
			default:
				exit("<xml><return_code>FAIL</return_code></xml>");
		}
	}
	
	/**
	 * 转化为可提交的订单格式
	 * @param unknown $order
	 */
	protected function parseOrder($order) {
		$vo = new \Utuo\Pay\PayVo;
		$vo->setOrderNo($order['order_no']);
		$vo->setFee($order['actual_cost']);
		$body = "";
		foreach ( $order['orderItems'] as $productId => $product  ) {
			$body.= $product['productName']."\r\n";
		}
		$vo->setBody( $body );
		$vo->setTitle("NO:".$order['order_no']);
		return $vo;
	}
	
	/**
	 * 支付成功时
	 * @param unknown $orderNo
	 * @param unknown $apitype
	 */
	protected function paySuccess($orderNo, $apitype) {
		$this->rwSeparate(0);
		$order = M("Order")->where("order_no='%s'", $orderNo)->find();
		$this->rwSeparate(1);
		if ( $order['pay_status'] == OrderModel::PAY_STATUS_NOT_PAID ) {
			/* 支付状态更新 */
			M("Order")->where("id=%d", $order['id'])
					  ->save(array(
    						"pay_time" => time(),
    						"order_status" => OrderModel::ORDER_STATUS_SHIPPING,
    						"pay_method" => $apitype,
    						"pay_status" => OrderModel::PAY_STATUS_PAID,
					  ));
		}
	}
	
	/**
	 * 获得接口配置
	 * @param array $cfg
	 * array(
	 * 	'paymentMethod', // 支付方式(*): Alipay,WxTenpay
	 * )
	 * @return array
	 */
	protected function getApiConfig( $cfg ) {
		// 支付通知地址
		$config = PayLogic::getApiConfig( $this->cid, $cfg );
		$config['return_url'] = $config['notify_url'] = PayLogic::getCallBackUrl($cfg['paymentMethod'], $this->cid, null, null, $config['debug']*1);
		return $config;
	}
	
}